#include <at89x52.h>
#include "config.h"
#include "uart.h"
#include <stdio.h>

volatile uint8_t Sending;
code uint8_t HexTable[] = {'0', '1', '2', '3', '4', '5', '6', '7', \
						   '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

/**************************************************
function:uart init
input: none
return: none
note: note
**************************************************/
void InitUart(void)
{
	EA = 0;
	TMOD &= 0x0F;
	TMOD |= 0x20;
	SCON = 0x50;
	TH1 = 256 -Fclk/(BitRate*12*16);
	TL1 = 256 -Fclk/(BitRate*12*16);
	PCON |= 0x80;
	ES = 1;
	TR1 = 1;
	REN = 1;
	EA = 1;
}

/***************************************************
function:uart interrupt handle
input: None
return: None
Note: None
***************************************************/
void UartISR(void) interrupt 4
{
	if(RI)  // recved data
	{
		RI = 0; // clean req flag
	}
	else	// send done one byte.
	{
		TI = 0;
		Sending = 0;	// clean sending data flags.
	}
}

/**************************************************
function:send one byte to uart
input: b,need sned one byte
return: None
Note: None
**************************************************/
void UartPutChar(uint8_t d)
{
	SBUF = d;		// put data uart buffer.
	Sending = 1;	// set send data flag
	while(Sending);	// waiting send done.
}

char putchar(char c)
{
	UartPutChar(c);
	return c;
}

// int fputc(int ch, FILE* f)
// {
// 	UartPutChar(ch);
// 	return ch;
// }

/*************************************************
function: send string by uart
input: pd, need send string ptr
return:None
Note: None
*************************************************/
void Prints(uint8_t* pd)
{
	while((*pd) != '\0')
	{
		UartPutChar(*pd);
		pd++;
	}
}

/*************************************************
function: send short int by hex format
input:need send short int
return:None
Note:None
*************************************************/
#if 0
void PrintShortIntHex(uint16_t x)
{
	uint8_t i;
	uint8_t display_buffer[7];
	display_buffer[6] = 0;
	display_buffer[0] = '0';
	display_buffer[1] = 'x';
	for(i=5;i>=2;i--){
		display_buffer[i] = HexTable[(x&0xf)];
		x>>= 4;
	}
	Prints(display_buffer);
}
#endif

void PrintHex(uint8_t x)
{
	UartPutChar('0');
	UartPutChar('x');
	UartPutChar(HexTable[x>>4]);
	UartPutChar(HexTable[x&0xf]);
	UartPutChar(' ');
}

void PrintLongInt(uint32_t x)
{
	int8_t i = 0;
	uint8_t display_buffer[10];
	for(i = 9; i >= 0; i--) {
		display_buffer[i] = '0' + x % 10;
		x /= 10;
	}

	for(i = 0; i < 9; i++) {
		if(display_buffer[i] != '0') break;
	}

	for(;i < 10; i++) UartPutChar(display_buffer[i]);
}

